package com.gzhryc.shared_device.oem.micro.iot.times;

import com.gzhryc.common.DateTools;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.common.redis.RedisTools;
import com.gzhryc.shared_device.cdcz.code.dao.db.ChargeSocket;
import com.gzhryc.shared_device.cdcz.code.services.ChargeSocketService;
import com.gzhryc.shared_device.oem.code.RedisDBConstants;
import com.gzhryc.shared_device.oem.code.device.CDCZCacheManager;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import redis.clients.jedis.Jedis;

import java.util.Date;
import java.util.Set;

public class CDCZOnlineCheckJob implements Job {

    static Logger log = Logger.getLogger(CDCZOnlineCheckJob.class);

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        Jedis jedis = RedisTools.get().getJedis();
        if(jedis != null) {
            try {
                jedis.select(RedisDBConstants.CDCZ_DEVICE_DB);
                Set<String> keys = jedis.keys("*");
                log.info("每5分钟检查充电插座心跳状态，缓存数量：" + keys.size());
                if (keys != null && keys.size() > 0) {
                    CDCZCacheManager cacheManager = new CDCZCacheManager();
                    for (String key : keys) {
                        String json = jedis.get(key);
                        if (JsonTools.isJsonStr(json)) {
                            ChargeSocket chargeSocket = JsonTools.fromJson(json, ChargeSocket.class);
                            boolean flag = true;
                            if (chargeSocket.getHeartbeatData() != null) {
                                Long minute = DateTools.differenceMinute(chargeSocket.getHeartbeatData(), new Date());
                                if (minute <= 5) {
                                    flag = false;
                                }
                            }
                            if (flag) {
                                cacheManager.removeChargeSocket(key);
                                ChargeSocketService.self().offline(key);
                                log.info("充电插座设备【" + key + "】心跳超时下线，缓存内容：{{0:json}}", chargeSocket);
                            }
                        }
                    }
                }
            } finally {
                jedis.close();
            }
        }
    }
}
